package com.demo.xzbd.controller;

import com.demo.xzbd.excel.ExcelUtils;
import com.demo.xzbd.file.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * excel 导出
 * sun 2017-10-27
 */
@RestController(value = "excelController")
@RequestMapping("excel-opi/v1/excel/")
public class ExcelController {
    private Logger logger = Logger.getLogger(ExcelController.class);

    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public void downloadExcel( HttpServletResponse response){
        try {
            String fileDir = "/templates/reportCard/STUDENT-REPORT-CARD" + ExcelUtils.EXCELSUFFIX_2007U;
            File file = FileUtils.getFile(fileDir);
//            ByteArrayOutputStream os = new ByteArrayOutputStream();
//            String title = "";
//            Map headMap = new HashMap<String,String>();
//
//            JSONArray ja = new JSONArray();
//            ExcelUtils.exportExcelX(title,headMap,ja,null,0,os);
//            byte[] content = os.toByteArray();
//            InputStream is = new ByteArrayInputStream(content);
            InputStream is = new FileInputStream(file);
            // 设置response参数，可以打开下载页面
            response.reset();
            Date d = new Date();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String(( d.getTime()+ ExcelUtils.EXCELSUFFIX_2007U).getBytes(), "iso-8859-1"));
            response.setContentLength(Integer.valueOf(file.length()+""));
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(outputStream);
            byte[] buff = new byte[8192];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
            outputStream.flush();
            outputStream.close();

        }catch (Exception e){
            logger.error("excel download error! ",e);
        }
    }
}
